package eu.connect.im;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.Socket;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.echomine.common.ParseException;
import com.echomine.jabber.JabberMessage;

public class XMPPProxyThread extends Thread implements Partner
{
	private String role;
	private Socket socket;
	private MessageQueue queue;
	private BufferedReader br;
	private BufferedWriter bw;
	private XMPPMsgFilterThread msgFilterThread;
	
	
	public XMPPProxyThread(String role, Socket socket, MessageQueue queue)
	{
		super();
		
		this.role = role;
		this.socket = socket;
		this.queue =queue;
	
		PipedInputStream pipeIn = new PipedInputStream();
    	PipedOutputStream pipeOut = new PipedOutputStream();
		
		try
		{
			pipeOut.connect(pipeIn);
			msgFilterThread = new XMPPMsgFilterThread(this.role, this.socket.getInputStream(), pipeOut);
			msgFilterThread.setDaemon(true);
			msgFilterThread.start();
			br = new BufferedReader(new InputStreamReader(pipeIn, "UTF8"), 8192);
			bw = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "UTF8"), 8192);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public void run()
	{
		try
		{
			SAXParserFactory parserFactory = SAXParserFactory.newInstance();
			parserFactory.setValidating(false);
			parserFactory.setNamespaceAware(true);
			XMPPContentHandler contentHandler = new XMPPContentHandler(this.role, this.queue);
			SAXParser parser = parserFactory.newSAXParser();
			parser.parse(new InputSource(this.br), contentHandler);
		}
	    catch(IOException ex) {
	    	//ex.printStackTrace();
	    }
	    catch(SAXException ex) {
	    	//ex.printStackTrace();
	    }
	    catch(ParserConfigurationException ex) {
	    	ex.printStackTrace();
	    }
	    catch(FactoryConfigurationError ex) {
	    	ex.printStackTrace();
	    }
	}
	
	@Override
	public void sendMessage(Message msg)
	{
		JabberMessage message = (JabberMessage)msg.getMessageEntity();
		try
		{
			this.bw.write(message.encode());
			this.bw.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		
	}
	
	public boolean isRunning()
	{
		return this.msgFilterThread.isAlive();
	}
	
	public void shutdown()
	{
		this.interrupt();
		this.msgFilterThread.interrupt();
	}
	
}
